package compare_atomic_mutex

import (
	"sync/atomic"
	"unsafe"
)

// P 定义一个struct类型P
type P struct{ x, y, z int }

// 执行类型P的指针
var pP *P

func CasDemo() (unsafe1 *unsafe.Pointer, old unsafe.Pointer, new P, success bool) {

	// 定义一个执行unsafe.Pointer值的指针变量
	unsafe1 = (*unsafe.Pointer)(unsafe.Pointer(&pP))

	// Old pointer
	//var sy P

	// 为了演示效果先将unsafe1设置成Old Pointer
	old = atomic.SwapPointer(
		unsafe1, unsafe.Pointer(&new))

	// 执行CAS操作，交换成功，结果返回true
	success = atomic.CompareAndSwapPointer(
		unsafe1, unsafe.Pointer(&new), old)

	return
}
